package tech.wangpai.microservice.product.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import tech.wangpai.microservice.product.domain.Product;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public class ProductMapper {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Product> queryUserByUsername(String pname){
        String sql = " SELECT pid,pname,type,price,createtime from products WHERE pname=?" ;
        return jdbcTemplate.query(sql,new Object[]{pname},new BeanPropertyRowMapper<Product>(Product.class));
    }

    public Product getProductById(String productId){
        String sql = "SELECT pid,pname,type,price,createtime from products WHERE pid = ?";
        RowMapper<Product> rowMapper = new BeanPropertyRowMapper<Product>(Product.class);
        return jdbcTemplate.queryForObject(sql, rowMapper, productId);
    }

    public void addProduct(Product product) {
        String sql = "INSERT INTO products (pid,pname,type,price,createtime) values(?,?,?,?,?)";
        jdbcTemplate.update(sql,product.getPid(),product.getPname(),product.getType(),product.getPrice(), LocalDateTime.now());
    }

    public void delProductById(String productId){
        String sql = "DELETE FROM products WHERE pid=?";
        jdbcTemplate.update(sql,productId);
    }

    public void updateProductById(Product product){
        String sql = "UPDATE products SET pname=?,type=?,price=? WHERE pid=?";
        jdbcTemplate.update(sql,product.getPname(),product.getType(),product.getPrice(), product.getPid());
    }
}
